<template>
  <div class="app-container">
    <div class="filter-container">
      <div class="search-container">
        <el-input v-model="listQuery.title" placeholder="请输入内容" style="width: 240px;margin-right:10px;" class="filter-item" @keyup.enter.native="handleFilter" />
        <el-button class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">
          查询
        </el-button>
        <el-button class="filter-item" style="margin-left: 10px;" type="success" icon="el-icon-edit" @click="handleCreate">
          新增
        </el-button>
      </div>
      <pagination v-show="total>0" :total="total" :page.sync="listQuery.pageNo" :layout="'total, sizes, prev, pager, next, jumper'" :limit.sync="listQuery.pageSize" @pagination="getDemandsList" />
    </div>

    <el-table
      :key="tableKey"
      v-loading="pageLoading"
      :data="listData"
      border
      fit
      :row-class-name="tableRowClassName"
      style="width: 100%;"
    >
      <el-table-column width="50" align="center">
        <template slot-scope="{row}"><el-checkbox :checked="row.status === 3 || row.progress === 100" :disabled="row.status === 3 || row.progress === 100" @change="handleCheckboxChange(row)" /></template>
      </el-table-column>
      <el-table-column label="名称" align="left">
        <template slot-scope="{row}">
          <span>{{ row.name }}</span>
        </template>
      </el-table-column>
      <el-table-column label="截止时间" width="100" align="center" sortable prop="deadline_at">
        <template slot-scope="{row}">
          <span>{{ row.deadline_at | golbalParseTimeFilter }}</span>
        </template>
      </el-table-column>
      <el-table-column label="执行人" width="180" align="center">
        <template slot-scope="{row}">
          <span v-if="!row.execute_by.length">-</span>
          <span v-for="(user, idx) of row.execute_by" :key="user.id">{{ user.nickname }}{{ idx === row.execute_by.length - 1 ? '' : '、' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="创建人" width="100" align="center">
        <template slot-scope="{row}">
          <span>{{ row.created_by.nickname }}</span>
        </template>
      </el-table-column>
      <el-table-column label="优先级" width="80" align="center" sortable prop="priority">
        <template slot-scope="{row}">
          <el-tag effect="dark" :type="row.priority | golbalPriorityFilter">
            {{ row.priority | golbalPriorityNameFilter }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="状态" class-name="status-col" width="80" sortable prop="status">
        <template slot-scope="{row}">
          <el-tag effect="light" :type="row.status | golbalStatusFilter">
            {{ row.status | golbalStatusNameFilter }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="进度(%)" width="50" align="center">
        <template slot-scope="{row}">
          <span>{{ row.progress }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="120" class-name="small-padding fixed-width">
        <template slot-scope="{row,$index}">
          <el-button type="text" @click.stop="handleUpdate(row)">
            编辑
          </el-button>
          <el-button v-if="row.status!='deleted'" style="color: #F56C6C;" type="text" @click="handleDelete(row,$index)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible" :close-on-click-modal="false" :width="'50vw'">
      <el-form ref="dataForm" :rules="rules" :inline="true" :model="temp" label-position="right" label-width="80px">
        <el-form-item label="名称" prop="name">
          <el-input v-model="temp.name" type="textarea" :autosize="{ minRows: 2, maxRows: 4}" placeholder="Tips：描述可以粘贴图片" style="width:calc(50vw - 140px)" />
        </el-form-item>
        <br>
        <el-form-item label="开始时间" prop="start_at">
          <el-date-picker v-model="temp.start_at" type="datetime" format="yyyy-MM-dd HH:mm" default-time="09:00:00" value-format="yyyy-MM-dd HH:mm:ss" placeholder="请选择时间" />
        </el-form-item>
        <el-form-item label="截止时间" prop="deadline_at">
          <el-date-picker
            v-model="temp.deadline_at"
            type="datetime"
            format="yyyy-MM-dd HH:mm"
            default-time="18:00:00"
            value-format="yyyy-MM-dd HH:mm:ss"
            placeholder="请选择时间"
          />
        </el-form-item>
        <el-form-item label="执行人" prop="execute_by">
          <el-select v-model="temp.execute_by" multiple class="filter-item" placeholder="请选择" @change="$forceUpdate()">
            <el-option v-for="item in usersOptions" :key="item.id" :label="item.nickname" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="优先级" prop="priority">
          <el-select v-model="temp.priority" class="filter-item" placeholder="请选择" @change="$forceUpdate()">
            <el-option v-for="item in priorityOptions" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="temp.status" class="filter-item" placeholder="请选择" @change="handleStatusProgress">
            <el-option v-for="item in statusOptions" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="进度(%)" prop="progress">
          <el-input-number v-model="temp.progress" controls-position="right" :min="0" :max="100" />
        </el-form-item>
        <el-form-item label="创建时间" prop="created_at">
          <el-date-picker v-model="temp.created_at" disabled type="datetime" format="yyyy-MM-dd HH:mm" default-time="09:00:00" value-format="yyyy-MM-dd HH:mm:ss" placeholder="请选择时间" />
        </el-form-item>
        <el-form-item label="完成时间" prop="complete_at">
          <el-date-picker v-model="temp.complete_at" disabled type="datetime" format="yyyy-MM-dd HH:mm" default-time="09:00:00" value-format="yyyy-MM-dd HH:mm:ss" placeholder="请选择时间" />
        </el-form-item>
        <br>
        <el-form-item label="描述">
          <div ref="introTextarea" class="input-textarea" contenteditable placeholder="请输入" style="width:calc(50vw - 140px)" @paste="handlePaste" />
          <!-- <el-input v-model="temp.intro" :autosize="{ minRows: 2, maxRows: 4}" type="textarea" placeholder="请输入" /> -->
        </el-form-item>
        <br>
        <el-radio-group v-if="$route.params.id === 'c1n6sd9n7b2ar5b1a8pg'" v-model="aftersale" @change="handleChangeAfterSale">
          <el-radio-button label="普通">普通模版</el-radio-button>
          <el-radio-button label="发货">发货模版</el-radio-button>
          <el-radio-button label="订单">订单模版</el-radio-button>
        </el-radio-group>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          取消
        </el-button>
        <el-button type="primary" :disabled="delayBtn" @click="dialogStatus==='create'?createData():updateData()">
          确认
        </el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import { parseTime, resizeImage } from '@/utils'
import Pagination from '@/components/Pagination'
import { AfterSaleTemplate, onChangeSelect } from './aftersale-template'
import { OrderTemplate, onChangeSelect2 } from './order-template'
import * as UserApi from '@/api/user'
import * as DemandApi from '@/api/demand'

export default {
  name: 'Demands',
  components: { Pagination },
  props: {
    head: {
      type: Object,
      default: () => {
        return {}
      }
    }
  },
  data() {
    return {
      tableKey: 0,
      total: 0,
      pageLoading: false,
      ownDrawer: false,
      delayBtn: false,
      drawerDirection: 'rtl',
      detailData: {},
      usersOptions: [],
      aftersale: '普通',
      priorityOptions: [
        {
          id: 1,
          name: '非常高'
        },
        {
          id: 2,
          name: '高'
        },
        {
          id: 3,
          name: '一般'
        },
        {
          id: 4,
          name: '低'
        }
      ],
      statusOptions: [
        {
          id: 1,
          name: '未开始'
        },
        {
          id: 2,
          name: '进行中'
        },
        {
          id: 3,
          name: '已完成'
        },
        {
          id: 4,
          name: '取消'
        }
      ],
      listQuery: {
        pageNo: 1,
        pageSize: 10,
        project_id: ''
      },
      listData: [],
      temp: {
        name: '',
        intro: '',
        weight: '',
        status: 1,
        progress: 0,
        priority: 3,
        execute_by: [],
        start_at: '',
        created_at: '',
        complete_at: '',
        deadline_at: ''
      },
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: '编辑',
        create: '创建'
      },
      rules: {
        name: [{ required: true, message: '必须填写名称', trigger: 'blur' }],
        execute_by: [{ required: true, message: '必须填写执行人', trigger: 'blur' }]
      }
    }
  },
  mounted() {
    this.getDemandsList()
    this.getUsers()
  },
  methods: {
    async getDemandsList(pageQuery) {
      if (pageQuery) {
        this.listQuery = Object.assign(this.listQuery, pageQuery)
      }
      this.listData = []
      this.pageLoading = true
      this.listQuery['project_id'] = this.$route.params.id
      const { data } = await DemandApi.getDemands(this.listQuery)
      if (data && data.total) {
        this.listData = data.items
        this.total = data.total
      }
      this.pageLoading = false
    },
    async getUsers() {
      const { data } = await UserApi.getUserList({ pageNo: 1, pageSize: 99 })
      if (data && data.total) {
        this.usersOptions = data.items
      }
    },
    validateStartEndTime(temp) {
      if (!temp.start_at || !temp.deadline_at) return true
      // Safari 日期格式处理
      if (/Safari/.test(navigator.userAgent) && !/Chrome/.test(navigator.userAgent)) {
        return new Date(temp.start_at.replaceAll(/-/g, '/')).getTime() < new Date(temp.deadline_at.replaceAll(/-/g, '/')).getTime()
      }
      return new Date(temp.start_at).getTime() < new Date(temp.deadline_at).getTime()
    },
    tableRowClassName({ row }) {
      if (row.status === 4) {
        return 'grey-row'
      } else if (row.status === 3 || row.progress === 100) {
        if (new Date(row.deadline_at).getTime() - new Date(row.complete_at).getTime() < 0) {
          return 'not-done-row'
        }
        return 'done-row'
      } else if (new Date(row.deadline_at).getTime() - new Date().getTime() < 0) {
        return 'not-done-row'
      }
    },
    handleStatusProgress(val) {
      this.$forceUpdate()
      switch (val) {
        case 3:
          this.temp['progress'] = 100
          break
        default:
          this.temp['progress'] = 0
          break
      }
    },
    handleFilter() {
      this.listQuery.pageNo = 1
      this.getDemandsList()
    },
    curSorMoveEnd() {
      setTimeout(() => {
        window.getSelection()
        const range = document.createRange()
        range.selectNodeContents(this.$refs.introTextarea)
        range.collapse(false)
        const sel = window.getSelection()
        sel.removeAllRanges()
        sel.addRange(range)
      }, 0)
    },
    handlePaste(e) {
      const file = e.clipboardData.files[0]
      if (file && file.type.startsWith('image')) {
        e.preventDefault()
        resizeImage(file).then(res => {
          this.$refs.introTextarea.innerHTML += `<img style="max-width: 100%;cursor: pointer" src="${res}" />`
          this.curSorMoveEnd()
        })
      }
    },
    async handleCheckboxChange(row) {
      const temp = {}
      temp['id'] = row.id
      temp['name'] = row.name
      temp['status'] = 3
      temp['weight'] = row.weight
      temp['intro'] = row.intro
      temp['priority'] = row.priority
      temp['progress'] = 100
      temp['execute_by'] = (row.execute_by.length && row.execute_by.map(item => { return item.id })) || []
      temp['deadline_at'] = row.deadline_at
      temp['complete_at'] = parseTime(new Date())
      temp['start_at'] = row.start_at
      temp['created_by'] = row.created_by
      temp['project_id'] = row.project
      const { data } = await DemandApi.updateDemand(temp)
      if (data) {
        await this.getDemandsList()

        await this.$notify({
          title: 'Success',
          message: '更新成功',
          type: 'success',
          duration: 2000
        })
      }
    },
    handleChangeAfterSale(val) {
      if (val === '发货') {
        this.temp['name'] = '【发货】' + this.temp['name']
        this.$refs.introTextarea.innerHTML = AfterSaleTemplate + this.$refs.introTextarea.innerHTML
        onChangeSelect()
      } else if (val === '订单') {
        this.temp['name'] = '【订单】' + this.temp['name']
        this.$refs.introTextarea.innerHTML = OrderTemplate + this.$refs.introTextarea.innerHTML
        onChangeSelect2()
      } else {
        this.temp['name'] = ''
        this.$refs.introTextarea.innerHTML = ''
      }
    },
    resetTemp() {
      this.temp = {
        name: '',
        intro: '',
        weight: '',
        status: 1,
        priority: 3,
        progress: 0,
        execute_by: [],
        project_id: this.$route.params.id,
        deadline_at: '',
        created_at: '',
        complete_at: '',
        start_at: ''
      }
      setTimeout(() => {
        if (this.$refs.introTextarea) {
          this.$refs.introTextarea.innerHTML = ''
        }
      }, 0)
    },
    async handleCreate() {
      this.resetTemp()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true

      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    createData() {
      this.$refs['dataForm'].validate(async(valid) => {
        const timeValid = this.validateStartEndTime(this.temp)
        if (!timeValid) {
          await this.$message.error('截止时间必须大于开始时间！')
          return
        }
        if (valid) {
          this.temp['intro'] = this.$refs.introTextarea.innerHTML
          this.temp['complete_at'] = (this.temp['status'] === 3 || this.temp['progress'] === 100) ? parseTime(new Date()) : null

          this.delayBtn = true
          const { data } = await DemandApi.createDemand(this.temp)
          if (data) {
            await this.getDemandsList()

            this.dialogFormVisible = false
            await this.$notify({
              title: 'Success',
              message: '新增成功',
              type: 'success',
              duration: 2000
            })
          }
          this.delayBtn = false
        }
      })
    },
    async handleUpdate(row) {
      setTimeout(() => {
        if (row.name.includes('【发货】')) {
          this.aftersale = '发货'
          onChangeSelect()
        } else if (row.name.includes('【订单】')) {
          this.aftersale = '订单'
          onChangeSelect2()
        } else {
          this.aftersale = '普通'
        }
      }, 1e3)
      this.temp['id'] = row.id
      this.temp['name'] = row.name
      this.temp['status'] = row.status
      this.temp['weight'] = row.weight
      this.temp['intro'] = row.intro
      this.temp['priority'] = row.priority
      this.temp['progress'] = row.progress
      this.temp['execute_by'] = (row.execute_by.length && row.execute_by.map(item => { return item.id })) || []
      this.temp['deadline_at'] = row.deadline_at
      this.temp['start_at'] = row.start_at
      this.temp['created_at'] = row.created_at
      this.temp['complete_at'] = row.complete_at
      this.temp['created_by'] = row.created_by
      this.temp['project_id'] = row.project
      setTimeout(() => {
        if (this.$refs.introTextarea) {
          this.$refs.introTextarea.innerHTML = row.intro
        }
      }, 0)

      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    updateData() {
      this.$refs['dataForm'].validate(async(valid) => {
        const timeValid = this.validateStartEndTime(this.temp)
        if (!timeValid) {
          await this.$message.error('截止时间必须大于开始时间！')
          return
        }
        if (valid) {
          this.temp['review_by'] = this.head.id
          this.temp['complete_at'] = (this.temp.status === 3 || this.temp.progress === 100) ? parseTime(new Date()) : null
          this.temp['intro'] = this.$refs.introTextarea.innerHTML

          this.delayBtn = true
          const { data } = await DemandApi.updateDemand(this.temp)
          if (data) {
            await this.getDemandsList()
            this.dialogFormVisible = false
            await this.$notify({
              title: 'Success',
              message: '更新成功',
              type: 'success',
              duration: 2000
            })
          }
          this.delayBtn = false
        }
      })
    },
    handleDelete(row, index) {
      this.$confirm('此操作删除该项, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async() => {
        await DemandApi.deleteDemand(row.id)
        await this.getDemandsList()

        await this.$notify({
          title: 'Success',
          message: '删除成功！',
          type: 'success',
          duration: 2000
        })
      }).catch(err => {
        console.error(err)
        this.$notify({
          title: 'Fail',
          message: '已取消删除',
          type: 'error',
          duration: 2000
        })
      })
    }
  }
}
</script>

<style scoped>
.el-table /deep/ .done-row {
  background: #f0f9eb;
}
.el-table /deep/ .not-done-row {
  background: #fde9e9;
}
.el-table /deep/ .grey-row {
  background: #EBEEF5;
}
.filter-container {
  display: flex;
  justify-content: space-between;
}
.el-table .warning-row {
  background: #606266;
}
.pagination {
  display: flex;
  justify-content: center;
  margin-top: 1rem;
}
.temp-table {
  width: 100%;
}
.input-textarea {
  display: block;
  width: 100%;
  box-sizing: border-box;
  flex: auto;
  border: 1px solid #ccc;
  border-radius: 5px;
  padding: 0.5rem;
  min-height: 8rem;
  max-height: 12rem;
  line-height: 1.4;
  font-size: 1rem;
  resize: none;
  background: none;
  overflow-x: hidden;
  overflow-y: auto;
}
</style>
